package com.shop.servlet;

import com.shop.bean.Cart;
import com.shop.bean.CartItem;
import com.shop.bean.Goods;
import com.shop.service.GoodsService;
import com.shop.service.impl.GoodsServiceImpl;
import com.shop.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author WuLiangHang
 */
@WebServlet("/cart.do")
public class CartServlet extends BaseServlet {
    GoodsService goodsService = new GoodsServiceImpl();

    /**
     * 加入购物车
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        //获取请求参数 商品编号
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        Goods goods = goodsService.queryGoodsById(id);
        //把商品信息 转换成为CartItem商品项
        CartItem cartItem = new CartItem(goods.getId(), goods.getName(), 1, goods.getPrice(), goods.getPrice());
        //调用Cart.addItem 添加商品项
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            req.getSession().setAttribute("cart", cart);
        }
        cart.addItem(cartItem);
        System.out.println(cart);
        System.out.println("请求头Referer 的值：" + req.getHeader("Referer"));
        //重定向回原来商品所在的地址页面
        resp.sendRedirect(req.getHeader("Referer"));
    }
}
